package com.example.rabc.controller;

import com.example.rabc.common.ApiResponse;
import com.example.rabc.config.PermissionRequired;
import com.example.rabc.dto.UserCreateRequest;
import com.example.rabc.dto.UserUpdateRequest;
import com.example.rabc.entity.User;
import com.example.rabc.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 创建用户
     * @param request 用户创建请求对象
     * @return 包含创建用户的ApiResponse对象
     */
    @PermissionRequired("USER_CREATE")
    @PostMapping
    public ResponseEntity<ApiResponse<User>> createUser(
            @Valid @RequestBody UserCreateRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setEmail(request.getEmail());
        user.setRealName(request.getRealName());

        User createdUser = userService.createUser(user, request.getRoleCodes());
        return ResponseEntity.ok(ApiResponse.success(createdUser));
    }

    /**
     * 更新用户
     * @param userId 用户ID
     * @param request 用户更新请求对象
     * @return 包含更新用户的ApiResponse对象
     */
    @PutMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> updateUser(
            @PathVariable Long userId,
            @Valid @RequestBody UserUpdateRequest request) {
        User user = new User();
        user.setEmail(request.getEmail());
        user.setRealName(request.getRealName());

        User updatedUser = userService.updateUser(userId, user, request.getRoleCodes());
        return ResponseEntity.ok(ApiResponse.success(updatedUser));
    }

    /**
     * 删除用户
     * @param userId 用户ID
     * @return 包含空ApiResponse对象的ResponseEntity
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Long userId) {
        userService.deleteUser(userId);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    /**
     * 获取用户详情
     * @param userId 用户ID
     * @return 包含用户详情的ApiResponse对象
     */
    @GetMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    /**
     * 获取所有用户
     * @return 包含所有用户的ApiResponse对象
     */
    @PermissionRequired("USER_MANAGE")
    @GetMapping
    public ResponseEntity<ApiResponse<List<User>>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(ApiResponse.success(users));
    }

    /**
     * 为用户分配角色
     * @param userId 用户ID
     * @param roleCodes 角色代码集合
     * @return 包含操作结果的ApiResponse对象
     */
    @PostMapping("/{userId}/roles")
    public ResponseEntity<ApiResponse<Boolean>> assignRoles(
            @PathVariable Long userId,
            @RequestBody Set<String> roleCodes) {
        boolean result = userService.assignRolesToUser(userId, roleCodes);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 从用户移除角色
     * @param userId 用户ID
     * @param roleCodes 角色代码集合
     * @return 包含操作结果的ApiResponse对象
     */
    @DeleteMapping("/{userId}/roles")
    public ResponseEntity<ApiResponse<Boolean>> removeRoles(
            @PathVariable Long userId,
            @RequestBody Set<String> roleCodes) {
        boolean result = userService.removeRolesFromUser(userId, roleCodes);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 根据角色获取用户列表
     * @param roleCode 角色代码
     * @return 包含用户列表的ApiResponse对象
     */
    @GetMapping("/role/{roleCode}")
    public ResponseEntity<ApiResponse<List<User>>> getUsersByRole(@PathVariable String roleCode) {
        List<User> users = userService.getUsersByRole(roleCode);
        return ResponseEntity.ok(ApiResponse.success(users));
    }
}